package com.netease.nim.chatroom.demo.education.fragment;

import android.Manifest;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.chatroom.demo.R;
import com.netease.nim.chatroom.demo.base.ui.TFragment;
import com.netease.nim.chatroom.demo.base.util.log.LogUtil;
import com.netease.nim.chatroom.demo.education.adapter.ChatRoomTabPagerAdapter;
import com.netease.nim.chatroom.demo.education.helper.ChatRoomMemberCache;
import com.netease.nim.chatroom.demo.im.config.UserPreferences;
import com.netease.nim.chatroom.demo.im.session.ModuleProxy;
import com.netease.nim.chatroom.demo.im.ui.dialog.EasyAlertDialogHelper;
import com.netease.nim.chatroom.demo.im.ui.tab.FadeInOutPageTransformer;
import com.netease.nim.chatroom.demo.im.ui.tab.PagerSlidingTabStrip;
import com.netease.nim.chatroom.demo.permission.MPermission;
import com.netease.nim.chatroom.demo.permission.annotation.OnMPermissionDenied;
import com.netease.nim.chatroom.demo.permission.annotation.OnMPermissionGranted;
import com.netease.nim.chatroom.demo.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nim.chatroom.demo.permission.util.MPermissionUtil;
import com.netease.nim.chatroom.demo.thirdparty.live.LivePlayer;
import com.netease.nim.chatroom.demo.thirdparty.live.LiveSurfaceView;
import com.netease.nim.chatroom.demo.thirdparty.video.NEVideoController;
import com.netease.nim.chatroom.demo.thirdparty.video.NEVideoView;
import com.netease.nim.chatroom.demo.thirdparty.video.VideoPlayer;
import com.netease.nim.chatroom.demo.thirdparty.video.constant.VideoConstant;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;

import java.util.List;

/**
 * Created by hzxuwen on 2016/2/29.
 */
public class ChatRoomFragment extends TFragment implements ViewPager.OnPageChangeListener, LivePlayer.ActivityProxy,
        VideoPlayer.VideoPlayerProxy {
    private final String TAG = "ChatRoomFragment";
    private final int LIVE_PERMISSION_REQUEST_CODE = 100;

    private String roomId;
    private boolean liveMode; // true 直播模式，false 拉流模式
    private boolean disconnected = false; // 是否断网（断网重连用）

    /**
     * 聊天室TAB（下）
     */
    private PagerSlidingTabStrip tabs;
    private ViewPager viewPager;
    private ChatRoomTabPagerAdapter adapter;
    private int scrollState;

    /**
     * 直播区域（上）
     */
    private FrameLayout videoLayout; // 直播/播放区域
    private TextView statusText;
    private TextView roomIdText;
    private TextView videoInvalidStatusView;
    private ImageView backgroundImage;

    /**
     * 拉流播放
     */
    private VideoPlayer videoPlayer;
    private ModuleProxy moduleProxy;
    private String url;

    /**
     * 直播推流
     */
    private LivePlayer livePlayer;
    private View liveLayout;
    private Button startStopLiveBtn;
    private ImageView cameraImage;

    /**
     * ********************************** 生命周期 **********************************
     */

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.chat_room_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        findViews();
        setupPager();
        setupTabs();
    }

    @Override
    public void onResume() {
        super.onResume();

        if(videoPlayer != null) {
            videoPlayer.onActivityResume();
        }

        if(livePlayer != null) {
            livePlayer.onActivityResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if(videoPlayer != null) {
            videoPlayer.onActivityPause();
        }

        if(livePlayer != null) {
            livePlayer.onActivityPause();
        }
    }

    @Override
    public void onDestroy() {
        if(livePlayer != null) {
            livePlayer.resetLive();
        }

        if (videoPlayer != null) {
            videoPlayer.resetVideo();
        }

        super.onDestroy();
    }

    public void onBackPressed() {
        if(livePlayer != null) {
            livePlayer.tryStop();
        }

        logoutChatRoom();
    }

    public void onKickOut() {
        if(livePlayer != null) {
            livePlayer.tryStop();
        }

        clearChatRoom();
    }

    private void logoutChatRoom() {
        EasyAlertDialogHelper.createOkCancelDiolag(getActivity(), null, getString(R.string.logout_confirm),
                getString(R.string.leave), getString(R.string.cancel), true,
                new EasyAlertDialogHelper.OnDialogActionListener() {
                    @Override
                    public void doCancelAction() {

                    }

                    @Override
                    public void doOkAction() {
                        NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
                        clearChatRoom();
                    }
                }).show();

    }

    private void clearChatRoom() {
        ChatRoomMemberCache.getInstance().clearRoomCache(roomId);
        getActivity().finish();
    }

    /**
     * ********************************** View初始化 **********************************
     */

    private void findViews() {
        // 直播区域
        videoLayout = findView(R.id.view_layout);
        backgroundImage = findView(R.id.background_image);
        roomIdText = findView(R.id.room_id);
        statusText = findView(R.id.online_status);
        findView(R.id.back_arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // 聊天室区域
        tabs = findView(R.id.chat_room_tabs);
        viewPager = findView(R.id.chat_room_viewpager);
    }


    // 初始化直播UI
    public void initLiveVideo(String roomId, String url, boolean isLive, ModuleProxy moduleProxy) {
        this.liveMode = isLive; // 直播模式还是播放模式
        this.roomId = roomId;
        if (liveMode) {
            roomIdText.setText(String.format("roomId: %s", roomId));
            initLive(url);
        } else {
            backgroundImage.setVisibility(View.GONE);
            roomIdText.setVisibility(View.GONE);
            this.moduleProxy = moduleProxy;
            this.url = url;
            requestLivePermission(); // 请求权限
        }
    }

    /**
     * ************************************ 学生端拉流(播放) ************************************
     */

    private void initVideo(ModuleProxy moduleProxy, String url) {
        videoInvalidStatusView = findView(R.id.video_status);

        NEVideoView videoView = findView(R.id.chat_room_view);
        ViewGroup mediaControllerView = findView(R.id.media_controller);
        NEVideoController mMediaController = new NEVideoController(getActivity(), videoLayout,
                mediaControllerView, moduleProxy, VideoConstant.VIDEO_SCALING_MODE_FIT);

        videoPlayer = new VideoPlayer(getActivity(), videoView, mMediaController, url,
                UserPreferences.getPlayerStrategy(), this, VideoConstant.VIDEO_SCALING_MODE_FIT);

        videoPlayer.openVideo();
    }

    public void onVideoStatusChanged(boolean prepared) {
        videoInvalidStatusView.setVisibility(prepared ? View.GONE : View.VISIBLE);
    }

    /**
     * ************************************* 老师端推流(直播) ************************************
     */

    private void initLive(String url) {
        liveLayout = findView(R.id.live_layout);
        LiveSurfaceView liveView = findView(R.id.live_view);
        startStopLiveBtn = findView(R.id.StartStopAVBtn);
        cameraImage = findView(R.id.camera_image);

        livePlayer = new LivePlayer(liveView, url, this);

        showLiveUI();

        //控件的初始化
        initLiveButton();
    }

    private void showLiveUI() {
        backgroundImage.setVisibility(View.VISIBLE);
        startStopLiveBtn.setVisibility(View.VISIBLE);
    }

    // 初始化开始/停止直播/摄像头切换等按钮
    public void initLiveButton() {
        startStopLiveBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (disconnected) {
                    // 如果网络不通
                    Toast.makeText(getActivity(), R.string.net_broken, Toast.LENGTH_SHORT).show();
                    return;
                }

                requestLivePermission(); // 请求权限
            }
        });

        //切换前后摄像头按钮初始化
        cameraImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (livePlayer != null) {
                    livePlayer.switchCamera();
                }
            }
        });
    }

    // 权限控制
    private static final String[] LIVE_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE};

    private void requestLivePermission() {
        MPermission.with(ChatRoomFragment.this)
                .addRequestCode(LIVE_PERMISSION_REQUEST_CODE)
                .permissions(LIVE_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionGranted() {
        Toast.makeText(getActivity(), "授权成功", Toast.LENGTH_SHORT).show();
        if (liveMode) {
            if(livePlayer.startStopLive()) {
                hideLiveCover();
            }
        } else {
            initVideo(moduleProxy, url);
        }
    }

    @OnMPermissionDenied(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDenied() {
        List<String> deniedPermissions = MPermission.getDeniedPermissions(this, LIVE_PERMISSIONS);
        String tip = "您拒绝了权限" + MPermissionUtil.toString(deniedPermissions) + "，无法开启直播";
        Toast.makeText(getActivity(), tip, Toast.LENGTH_SHORT).show();
    }

    @OnMPermissionNeverAskAgain(LIVE_PERMISSION_REQUEST_CODE)
    public void onLivePermissionDeniedAsNeverAskAgain() {
        List<String> deniedPermissions = MPermission.getDeniedPermissionsWithoutNeverAskAgain(this, LIVE_PERMISSIONS);
        List<String> neverAskAgainPermission = MPermission.getNeverAskAgainPermissions(this, LIVE_PERMISSIONS);
        StringBuilder sb = new StringBuilder();
        sb.append("无法开启直播，请到系统设置页面开启权限");
        sb.append(MPermissionUtil.toString(neverAskAgainPermission));
        if(deniedPermissions != null && !deniedPermissions.isEmpty()) {
            sb.append(",下次询问请授予权限");
            sb.append(MPermissionUtil.toString(deniedPermissions));
        }

        Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_LONG).show();
    }

    private void hideLiveCover() {
        backgroundImage.setVisibility(View.GONE);
        liveLayout.setVisibility(View.VISIBLE);
        cameraImage.setVisibility(View.VISIBLE);
        startStopLiveBtn.setVisibility(View.GONE);
    }

    /**
     * ************************************ 聊天室 ************************************
     */

    private void setupPager() {
        // CACHE COUNT
        adapter = new ChatRoomTabPagerAdapter(getFragmentManager(), getActivity(), viewPager);
        viewPager.setOffscreenPageLimit(adapter.getCacheCount());
        // page swtich animation
        viewPager.setPageTransformer(true, new FadeInOutPageTransformer());
        // ADAPTER
        viewPager.setAdapter(adapter);
        // TAKE OVER CHANGE
        viewPager.setOnPageChangeListener(this);
    }

    private void setupTabs() {
        tabs.setOnCustomTabListener(new PagerSlidingTabStrip.OnCustomTabListener() {
            @Override
            public int getTabLayoutResId(int position) {
                return R.layout.chat_room_tab_layout;
            }

            @Override
            public boolean screenAdaptation() {
                return true;
            }
        });
        tabs.setViewPager(viewPager);
        tabs.setOnTabClickListener(adapter);
        tabs.setOnTabDoubleTapListener(adapter);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // TO TABS
        tabs.onPageScrolled(position, positionOffset, positionOffsetPixels);
        // TO ADAPTER
        adapter.onPageScrolled(position);
    }

    @Override
    public void onPageSelected(int position) {
        // TO TABS
        tabs.onPageSelected(position);

        selectPage(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // TO TABS
        tabs.onPageScrollStateChanged(state);

        scrollState = state;

        selectPage(viewPager.getCurrentItem());
    }

    private void selectPage(int page) {
        // TO PAGE
        if (scrollState == ViewPager.SCROLL_STATE_IDLE) {
            adapter.onPageSelected(viewPager.getCurrentItem());
        }
    }

    /**
     * ********************************** 断网重连处理 **********************************
     */

    public void onOnlineStatusChanged(boolean isOnline) {
        statusText.setVisibility(isOnline ? View.GONE : View.VISIBLE);
        if (isOnline) {
            onConnected();
        } else {
            onDisconnected();
        }
    }

    // 网络连接成功
    private void onConnected() {
        if (disconnected == false) {
            return;
        }

        LogUtil.i(TAG, "live on connected");

        if (!liveMode) {
            // 处理拉流
            LogUtil.i(TAG, "reopen video on connected");
            if(videoPlayer != null) {
                videoPlayer.openVideo();
            }
        } else {
            // 处理推流
            if(livePlayer != null) {
                if(livePlayer.restartLive()) {
                    hideLiveCover(); // 开始重连
                }
            }
        }

        disconnected = false;
    }

    // 网络断开
    private void onDisconnected() {
        LogUtil.i(TAG, "live on disconnected");

        if (!liveMode) {
            // 处理拉流
            onVideoStatusChanged(false);
        } else {
            // 处理推流
            showLiveUI();
            if(livePlayer != null) {
                livePlayer.stopLive();
            }
        }

        disconnected = true;
    }

    @Override
    public boolean isDisconnected() {
        return disconnected;
    }

    @Override
    public void onError() {
        onVideoStatusChanged(false);
    }

    @Override
    public void onCompletion() {
        onVideoStatusChanged(false);
        EasyAlertDialogHelper.showOneButtonDiolag(getActivity(), "Completed!", "播放结束",
                getString(R.string.ok), true, null);
    }

    @Override
    public void onPrepared() {
        onVideoStatusChanged(true);
    }
}
